﻿
using SuperSocialShare.Authorize;
using SuperSocialShare.Error;
using SuperSocialShare.Helper;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
namespace SuperSocialShare.Clients
{
    public class RenrenClient : SocialClient
    {
        protected override string AuthorizeUrl
        {
            get { return "https://graph.renren.com/oauth/authorize"; }
        }

        protected override string GetAccessTokenUrl
        {
            get { return "https://graph.renren.com/oauth/token"; }
        }

        protected override string GetUserInfoUrl
        {
            get { throw new NotImplementedException(); }
        }

        protected override string UpdateStatusUrl
        {
            get { return "https://api.renren.com/v2/status/put"; }
        }

        protected override string UploadImageUrl
        {
            get { return "https://api.renren.com/v2/photo/upload"; }
        }

        protected override string RevokeAuthorizeUrl
        {
            get { throw new NotImplementedException(); }
        }

        public override SocialType SocialType
        {
            get { return SocialType.Renren; }
        }

        protected override void GetAccessTokenAsync(string code)
        {
            HttpWebRequester requester = new HttpWebRequester();
            requester.Parameters.Add(new RequestParameter("client_id", ClientId));
            requester.Parameters.Add(new RequestParameter("client_secret", ClientSecret));
            requester.Parameters.Add(new RequestParameter("grant_type", "authorization_code"));
            requester.Parameters.Add(new RequestParameter("code", code));
            requester.Parameters.Add(new RequestParameter("redirect_uri", CallbackUrl));
            requester.RequestCompleted += requester_RequestCompleted;
            requester.BeginRequest(GetAccessTokenUrl, 0, "POST");
        }

        protected override void GetUserInfoAsync(AuthorizeInfo info)
        {
            throw new NotImplementedException();
        }


        internal override string GetRequestAuthorizeUrl()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>() 
            {
                {"client_id",ClientId},
              {"scope","publish_share status_update photo_upload"},   //read_user_photo
              {"display","touch"},
                {"response_type","code"},
                {"redirect_uri",CallbackUrl}
            };
            return Utility.BuildQueryString(AuthorizeUrl, parameters);
        }

        /// <summary>
        /// 处理请求授权后的返回数据，人人网的返回数据为authorize_code
        /// </summary>
        /// <param name="data"></param>
        internal override void ProcessResponseDataOfAuthorize(string data)
        {
            string code = string.Empty;
            string pattern = @"(?<=code=)[^&]*";
            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            Match match = regex.Match(data);
            if (match.Success)
                code = match.Value;

            HttpWebRequester requester = new HttpWebRequester();
            requester.Parameters.Add(new RequestParameter("client_id", ClientId));
            requester.Parameters.Add(new RequestParameter("client_secret", ClientSecret));
            requester.Parameters.Add(new RequestParameter("grant_type", "authorization_code"));
            requester.Parameters.Add(new RequestParameter("code", code));
            requester.Parameters.Add(new RequestParameter("redirect_uri", CallbackUrl));
            requester.RequestCompleted += requester_RequestCompleted;
            requester.BeginRequest(GetAccessTokenUrl, 0, "POST");
        }

        public override void RevokeAuthorizeAysnc()
        {
            throw new NotImplementedException();
        }

        public override void ShareText(string text)
        {
            RenrenAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as RenrenAuthorizeInfo;
            if (authorizeInfo != null)
            {
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
                requester.Parameters.Add(new RequestParameter("access_token", authorizeInfo.AccessToken));
                requester.Parameters.Add(new RequestParameter("content", text));

                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(UpdateStatusUrl, 1, "POST");
            }
        }

        public override void ShareTextWithImage(string text, byte[] imgdata)
        {
            RenrenAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as RenrenAuthorizeInfo;
            if (authorizeInfo != null)
            {
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.MULTIPART_FORM_DATA;
                requester.Parameters.Add(new RequestParameter("access_token", authorizeInfo.AccessToken));
                requester.Parameters.Add(new RequestParameter("albumId", 0));//相册id设为0，默认上传到应用相册
                requester.Parameters.Add(new RequestParameter("description", text));
                requester.Parameters.Add(new RequestParameter("file", imgdata));

                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(UploadImageUrl, 1, "POST");
            }
        }

        void requester_RequestCompleted(RequestCompletedEventArgs e)
        {
            AsyncEventArgs args = new AsyncEventArgs();
            int actionTag = Convert.ToInt32(e.UserData);
            if (e.Error == null)
            {
                RenrenError error = JsonConverter.GetObjectFromJsonString<RenrenError>(e.Result);
                if (error != null && error.ErrorCode != 0)
                {
                    args.Error = error;
                }

                if (actionTag == 0)//获取的数据accesstoken
                {
                    RenrenAuthorizeInfo info = JsonConverter.GetObjectFromJsonString<RenrenAuthorizeInfo>(e.Result);
                    if (info != null && !string.IsNullOrEmpty(info.AccessToken))
                    {
                        UserInfo user = new UserInfo();
                        user.Fill(e.Result, SocialType);
                        info.UserInfo = user;
                        args.Result = info;
                    }
                    OnGetAuthorizeInfoCompleted(args);
                }
                else//数据为分享操作后的返回数据
                {
                    OnShareCompleted(args);
                }
            }
            else//发生WebException 
            {
                args.Error = new ErrorBase(e.Error);
                if (actionTag == 0)
                {
                    OnGetAuthorizeInfoCompleted(args);
                }
                else
                {
                    OnShareCompleted(args);
                }
            }
        }
    }
}
